package org.thanos.demo.consumer;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.thanos.demo.topic.DemoTopic;

import java.nio.charset.StandardCharsets;
import java.util.UUID;


@Component
public class DemoMessageHandler implements MessageHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(DemoMessageHandler.class);

    @Autowired
    private MqttClient mqttClient;

    @Override
    public void consume() throws MqttException {

        mqttClient.subscribe(DemoTopic.TOPIC_NAME, DemoTopic.QOS);

        mqttClient.setCallback(new MqttCallback() {

            @Override
            public void connectionLost(Throwable e) {
                LOGGER.error(e.getMessage(), e);
            }

            @Override
            public void messageArrived(String topic, MqttMessage message) {
                LOGGER.info("topic:" + topic);
                LOGGER.info("Qos:" + message.getQos());
                String receiveMessage = new String(message.getPayload(), StandardCharsets.UTF_8);
                LOGGER.info("message content:" + receiveMessage);
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {
                LOGGER.info("deliveryComplete---------" + token.isComplete());
            }

        });
    }

    @Override
    public void produce() throws MqttException {
        mqttClient.publish(DemoTopic.TOPIC_NAME, UUID.randomUUID().toString().getBytes(), DemoTopic.QOS, false);
    }
}
